package com.juyu.miliao.scheduler.message;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.juyu.miliao.common.constant.BillDetailIntegralMqKey;
import com.juyu.miliao.common.constant.EnumType;
import com.juyu.miliao.common.constant.SpendSystemMessage;
import com.juyu.miliao.common.domain.BillDetailIntegral;
import com.juyu.miliao.common.domain.dto.BillDetailIntegralDTO;
import com.juyu.miliao.common.netease.NetEaseCloudUserService;
import com.juyu.miliao.scheduler.dao.mysql.IntegralLevelInfoDao;
import com.juyu.miliao.scheduler.dao.mysql.UserInfoDao;
import com.juyu.miliao.scheduler.dao.redis.UserIntegralRedis;
import com.juyu.miliao.scheduler.dao.mysql.BillDetailIntegralDao;
import com.juyu.miliao.scheduler.domin.IntegralLevelAndTitleDTO;
import com.juyu.miliao.scheduler.domin.User;
import com.juyu.miliao.scheduler.service.IntegralLevelInfoService;
import lombok.extern.slf4j.Slf4j;
import net.sf.json.JSONObject;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.Map;

/**
 * 添加账单
 * @author xuanqicheng
 */
@Component
@Slf4j
public class BillDetailIntegralMq {


    @Autowired
    private ObjectMapper objectMapper;

    @Autowired
    private AmqpTemplate amqpTemplate;

    @Autowired
    private BillDetailIntegralDao billDetailIntegralDao;

    @Autowired
    private UserIntegralRedis userIntegralRedis;
    @Autowired
    private UserInfoDao userInfoDao;
    @Autowired
    private IntegralLevelInfoService integralLevelInfoService;

    @RabbitListener(bindings = @QueueBinding(value = @Queue(BillDetailIntegralMqKey.CreateBillDetailIntegralKey.QUEUE_NAME),
            exchange = @Exchange(BillDetailIntegralMqKey.EXCHANGE),
            key = BillDetailIntegralMqKey.CreateBillDetailIntegralKey.ROUTING_KEY)
    )
    public void getBillDetailBeansMqMessage(String message) {
        if (!StringUtils.isEmpty(message)) {
            try {
                BillDetailIntegralDTO billDetailIntegralDTO = objectMapper.readValue(message,BillDetailIntegralDTO.class);
                BillDetailIntegral billDetailIntegral = new BillDetailIntegral();
                BeanUtils.copyProperties(billDetailIntegralDTO,billDetailIntegral);
                billDetailIntegralDao.insert(billDetailIntegral);
                //主播升级降级发送系统消息
                User user = userInfoDao.selectUserById(billDetailIntegral.getUserId());
                IntegralLevelAndTitleDTO userIntegralLevel = integralLevelInfoService.getUserIntegralLevel(user.getIntegralSum());
                String message1= SpendSystemMessage.HOST_USER_UPGRADE_SEND_MESSAGE.getMessage(userIntegralLevel.getIntegralGrade());
                String message2= SpendSystemMessage.HOST_USER_DOWNGRADE_SEND_MESSAGE.getMessage(userIntegralLevel.getIntegralGrade());
                if(!userIntegralRedis.checkIsUserIntegral(billDetailIntegral.getUserId())){
                    userIntegralRedis.addUserIntegral(billDetailIntegral.getUserId(),userIntegralLevel.getIntegralGrade());
                    //升级
                    sendMessageUserByIntegral(billDetailIntegral.getUserId(),message1);
                }else {
                     int redisIntegral = Integer.parseInt(userIntegralRedis.getUserIntegral(billDetailIntegral.getUserId()));
                    if(redisIntegral > userIntegralLevel.getIntegralGrade()){
                        userIntegralRedis.addUserIntegral(billDetailIntegral.getUserId(),userIntegralLevel.getIntegralGrade());
                        //降级
                        sendMessageUserByIntegral(billDetailIntegral.getUserId(),message2);
                    }else if(redisIntegral < userIntegralLevel.getIntegralGrade()){
                        //升级
                        userIntegralRedis.addUserIntegral(billDetailIntegral.getUserId(),userIntegralLevel.getIntegralGrade());
                        sendMessageUserByIntegral(billDetailIntegral.getUserId(),message1);
                    }
                }

            } catch (Exception ex) {
                log.error("处理积分账单据错误：" + message + "|erro=" + ex.getMessage());
            }
        }
    }

    public void getBillDetailIntegralMq(BillDetailIntegralDTO billDetailIntegralDTO){
        try {
            if (billDetailIntegralDTO != null) {
                amqpTemplate.convertAndSend(BillDetailIntegralMqKey.EXCHANGE,
                        BillDetailIntegralMqKey.CreateBillDetailIntegralKey.ROUTING_KEY,
                        objectMapper.writeValueAsString(billDetailIntegralDTO));
            }
        }catch (Exception ex){
            log.info("添加积分账单信息放入队列失败：{}", billDetailIntegralDTO);
        }
    }

    public void sendMessageUserByIntegral(long userId,String message) {

        try {
            log.info("发送系统消息通知：userId={},message={}", userId, message);
            Map<String, String> map = new HashMap<String, String>();
            map.put("title", "寻寻");
            map.put("type", "1");
            map.put("message", message);
            ObjectMapper mapper = new ObjectMapper();
            String createLogInfo= NetEaseCloudUserService.getSystemMessage(mapper.writeValueAsString(map), userId);
            if(!createLogInfo.substring(createLogInfo.indexOf("code")+6, createLogInfo.indexOf("code")+9).equals("200")){
                if(log.isErrorEnabled()){
                    log.error("主播等级系统消息发送IM失败：系统错误信息" + createLogInfo + "\n" + "参数：" + userId);
                }

            }
        } catch (Exception e) {
            log.error("主播等级系统消息发送IM错误：参数-" + userId,e);
        }
    }


}
